﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;

namespace PdfCombiner
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow
    {
        private string _txtSavedFilePath;
        private ObservableCollection<WorkItem> _items = new ObservableCollection<WorkItem>();
        public MainWindow()
        {
            InitializeComponent();
            LstView.ItemsSource = _items;
            TxtSavePath.Text = $@"{Environment.CurrentDirectory}\合并.pdf";
            _txtSavedFilePath = TxtSavePath.Text;
        }

        private void BtnUp_Click(object sender, RoutedEventArgs e)
        {
            var selectedItems = new WorkItem[LstView.SelectedItems.Count];
            LstView.SelectedItems.CopyTo(selectedItems, 0);
            foreach (var item in selectedItems)
            {
                var oldIndex = _items.IndexOf(item);
                if (oldIndex != 0)
                {
                    _items.Move(oldIndex, oldIndex - 1);
                }
            }
        }

        private void BtnDown_Click(object sender, RoutedEventArgs e)
        {
            var selectedItems = new WorkItem[LstView.SelectedItems.Count];
            LstView.SelectedItems.CopyTo(selectedItems, 0);
            foreach (var item in selectedItems.Reverse())
            {
                var oldIndex = _items.IndexOf(item);
                if (oldIndex < _items.Count - 1)
                {
                    _items.Move(oldIndex, oldIndex + 1);
                }
            }
        }

        private void BtnRemove_Click(object sender, RoutedEventArgs e)
        {
            var list = new WorkItem[LstView.SelectedItems.Count];
            LstView.SelectedItems.CopyTo(list, 0);
            foreach (var removeItem in list)
            {
                _items.Remove(removeItem);
            }
        }

        private void LstView_Drop(object sender, DragEventArgs e)
        {
            var files = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (files != null)
                foreach (var file in files)
                {
                    var fileInfo = new FileInfo(file);
                    if (fileInfo.Extension.ToLower() == ".pdf")
                    {
                        var workItem = new WorkItem
                        {
                            Title = fileInfo.Name,
                            Path = fileInfo.FullName,
                            Size = fileInfo.Length / 1024
                        };
                        _items.Add(workItem);
                    }
                }
        }

        //private static void Merge(List<WorkItem> inFiles, String outFile)
        //{
        //    using (FileStream stream = new FileStream(outFile, FileMode.Create))
        //    using (Document doc = new Document())
        //    using (PdfCopy pdf = new PdfCopy(doc, stream))
        //    {
        //        doc.Open();
        //        PdfReader reader;
        //        PdfReader.unethicalreading = true;
        //        PdfImportedPage page;
        //        //fixed typo
        //        inFiles.ForEach(file =>
        //        {
        //            reader = new PdfReader(file.Path);
                    
        //            for (int i = 0; i < reader.NumberOfPages; i++)
        //            {
        //                page = pdf.GetImportedPage(reader, i + 1);
        //                pdf.AddPage(page);
        //            }
        //            pdf.FreeReader(reader);
        //            reader.Close();
        //            //File.Delete(file);
        //        });
        //    }
        //}

        private void BtnBrowse_Click(object sender, RoutedEventArgs e)
        {
            var saveFileDlg = new Microsoft.Win32.SaveFileDialog
            {
                FileName = @"合并.pdf",
                DefaultExt = ".pdf",
                Filter = "PDF 文档 (.pdf)|*.pdf"
            };
            if (saveFileDlg.ShowDialog() == true)
            {
                TxtSavePath.Text = saveFileDlg.FileName;
                _txtSavedFilePath = TxtSavePath.Text;
            }
        }

        //private void Combine()
        //{
        //    var combineCnt = 0;
        //    var total = _items.Count;
        //    using (var stream = new FileStream(_txtSavedFilePath, FileMode.OpenOrCreate))
        //    using (var doc = new Document())
        //    using (var pdf = new PdfCopy(doc, stream))
        //    {
        //        doc.Open();
        //        PdfReader.unethicalreading = true;
        //        //fixed typo
        //        foreach (var item in _items)
        //        {
        //            var reader = new PdfReader(item.Path);

        //            for (int i = 0; i < reader.NumberOfPages; i++)
        //            {
        //                var page = pdf.GetImportedPage(reader, i + 1);
        //                pdf.AddPage(page);
        //            }
        //            pdf.FreeReader(reader);
        //            reader.Close();
        //            ++combineCnt;
        //            Dispatcher?.Invoke(new Action<int, int>((x, y) =>
        //            {
        //                ProCombine.Value = x;
        //                ProCombine.Maximum = y;
        //                LabelProgress.Content = $@"{x}/{y}";
        //            }), combineCnt, total);
        //        }
        //    }
        //    MessageBox.Show($@"{total}个文件合并完成。");
        //    Dispatcher?.Invoke(new Action(() =>
        //    {
        //        ProCombine.Visibility = Visibility.Hidden;
        //        LabelProgress.Visibility = Visibility.Hidden;
        //    }));
        //}
    

        private void BtnMerge_Click(object sender, RoutedEventArgs e)
        {
            if (_items.Count == 0)
            {
                MessageBox.Show("请选择需要合并的文件。");
                return;
            }
            //Merge(_items.ToList(), TxtSavePath.Text);
            //MessageBox.Show("合并完成。");
            ProCombine.Value = 0;
            ProCombine.Maximum = _items.Count;
            LabelProgress.Content = $@"0/{_items.Count}";
            ProCombine.Visibility = Visibility.Visible;
            LabelProgress.Visibility = Visibility.Visible;
            //var worker = new Thread(Combine);
            var worker = new Thread(() =>
            {
                var combineCnt = 0;
                var total = _items.Count;
                using (var stream = new FileStream(_txtSavedFilePath, FileMode.OpenOrCreate))
                using (var doc = new Document())
                using (var pdf = new PdfCopy(doc, stream))
                {
                    doc.Open();
                    PdfReader.unethicalreading = true;
                    foreach (var item in _items)
                    {
                        var reader = new PdfReader(item.Path);

                        for (int i = 0; i < reader.NumberOfPages; i++)
                        {
                            var page = pdf.GetImportedPage(reader, i + 1);
                            pdf.AddPage(page);
                        }
                        pdf.FreeReader(reader);
                        reader.Close();
                        ++combineCnt;
                        Dispatcher?.Invoke(new Action<int, int>((x, y) =>
                        {
                            ProCombine.Value = x;
                            ProCombine.Maximum = y;
                            LabelProgress.Content = $@"{x}/{y}";
                        }), combineCnt, total);
                    }
                }
                MessageBox.Show($@"{total}个文件合并完成。");
                Dispatcher?.Invoke(new Action(() =>
                {
                    ProCombine.Visibility = Visibility.Hidden;
                    LabelProgress.Visibility = Visibility.Hidden;
                }));
            });
            worker.Start();
        }

        private void BtnAbout_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(@"PDF合并程序v1.0，作者：yeshengyuan@foxmail.com", 
                @"关于", MessageBoxButton.OK, MessageBoxImage.Information);
        }
    }

    public class WorkItem
    {
        public string Title { get; set; }
        public string Path { get; set; }
        public long Size { get; set; }
    }
}
